<template>
    <div>
        <h1 class="pl-10 box-border h-8 w-full border-dashed border-b-2">文章管理</h1>
        <!-- 上面的筛选 -->
        <el-form :model="form" label-width="75px" label-position="right" :inline="true" ref="formRef"
            class="mb-5 border-dashed border-b-2">
            <el-form-item label="文章名字" prop="articlename">
                <el-input v-model="form.articlename" class=" m-2" placeholder="文章名字" maxlength="10">
                    <template #prefix>
                        <el-icon class="el-input__icon">
                            <search />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item label="文章标签" prop="labels">
                <el-select v-model="form.labels" placeholder="文章标签" style="width: 320px" clearable>
                            <el-option v-for="item in labels" :key="item.id" :label="item.lable_name"
                                :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="是否置顶" porp="article_istop">
                <el-select v-model="form.article_istop" placeholder="是否置顶" clearable>
                    <el-option label="是" :value="true" />
                    <el-option label="否" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择日期" prop="time">
                <el-date-picker class="" v-model="form.time" type="daterange" range-separator="To" start-placeholder="开始日期"
                    end-placeholder="结束日期" size="default" value-format="YYYY-MM-DD hh:mm:ss" />
            </el-form-item>
            <el-form-item class="ml-5">
                <el-button type="primary" @click="onSubmit($emit)">
                    <el-icon class="el-input__icon mr-2">
                        <search />
                    </el-icon>
                    搜索</el-button>
                <el-button @click="reset(formRef)">
                    <el-icon class="el-input__icon mr-2">
                        <refresh />
                    </el-icon>
                    取消</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章表格 -->
        <el-tabs type="border-card" v-model="activeName" @tab-change="handlechangepage">
            
            <el-tab-pane label="全部文章" :name="1">
                <el-skeleton  animated :loading="loading"></el-skeleton>
                        <el-table :data="tableData" style="width: 100%" v-loading="loading" max-height="330">
                    <el-table-column type="index" label="序号" width="70" />
                    <el-table-column prop="article_title" label="文章标题" width="120" />
                    <el-table-column prop="article_description" label="文章描述" width="110">
                        <template #default="scope">
                            <h1 class="text-ellipsis h-7 truncate ...">{{ scope.row.article_description }}</h1>
                        </template>
                    </el-table-column>
                    <el-table-column prop="lables" label="标签" width="130">
                        <template #default="scope">
                            <el-tag size="small" round :type="tag.type" v-for="tag in scope.row.lables" class="m-px">{{
                                tag.label }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="article_cover" label="封面" width="150">
                        <template #default="scope">
                            <el-image style="width: 120px; height: 70px" :src="scope.row.article_cover" fit="fill" 
                            :preview-src-list="[scope.row.article_cover]" :initial-index="0" :preview-teleported="true">
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon><icon-picture /></el-icon>
                                    </div>
                                </template>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="article_istop" label="是否置顶" width="120">
                        <template #default="scope">
                            <el-switch v-model="scope.row.article_istop" class="ml-2"
                                @change="handleChangeswitch(scope.row, scope.row.article_istop)" :active-value="true"
                                :inactive-value="false"
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdAt" label="发布时间" width="130">
                        <template #default="scope">
                            <div style="display: flex; align-items: center">
                                <el-icon>
                                    <timer />
                                </el-icon>
                                <span class="text-ellipsis h-6 truncate ...">{{ scope.row.createdAt }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="updatedAt" label="修改时间" width="130">
                        <template #default="scope">
                            <div style="display: flex; align-items: center">
                                <el-icon>
                                    <timer />
                                </el-icon>
                                <span class="text-ellipsis h-6 truncate ...">{{ scope.row.updatedAt }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="选项" width="120">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="editorarticle(scope.row)">编辑</el-button>
                            <el-button link type="primary" size="small" @click="AllhandleClick(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                        </el-table>
            </el-tab-pane>
            <el-tab-pane label="草稿箱" :name="2">
                <el-skeleton  animated :loading="loading"></el-skeleton>
                <el-table :data="tableData" style="width: 100%" v-loading="loading" max-height="330">
                    <el-table-column type="index" label="序号" width="80" />
                    <el-table-column prop="article_title" label="文章标题" width="140" />
                    <el-table-column prop="article_description" label="文章描述" width="140">
                        <template #default="scope">
                            <h1 class="text-ellipsis h-7 truncate ...">{{ scope.row.article_description }}</h1>
                        </template>
                    </el-table-column>
                    <el-table-column prop="lables" label="标签" width="140">
                        <template #default="scope">
                            <el-tag size="small" round :type="tag?.type" v-for="tag in scope.row.lables" class="m-px">{{
                                tag?.label }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="article_cover" label="封面" width="150">
                        <template #default="scope">
                            <el-image style="width: 120px; height: 70px" :src="scope.row.article_cover" fit="fill"
                                :preview-src-list="[scope.row.article_cover]" :initial-index="0" :preview-teleported="true">
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon><icon-picture /></el-icon>
                                    </div>
                                </template>
                            </el-image>

                        </template>
                    </el-table-column>
                    <el-table-column prop="updatedAt" label="修改时间" width="120">
                        <template #default="scope">
                            <div style="display: flex; align-items: center">
                                <el-icon>
                                    <timer />
                                </el-icon>
                                <span class="text-ellipsis h-6 truncate ...">{{ scope.row.updatedAt }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdAt" label="创建时间" width="130">
                        <template #default="scope">
                            <div style="display: flex; align-items: center">
                                <el-icon>
                                    <timer />
                                </el-icon>
                                <span class="text-ellipsis h-6 truncate ...">{{ scope.row.createdAt }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="选项" width="130">
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="editorarticle(scope.row)">编辑</el-button>
                            <el-button link type="primary" size="small" @click="AllhandleClick(scope.row)">永久删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>   
            </el-tab-pane>
            <pagination :currentPage="allcurrentPage" :pageSize="allpageSize" :total="alltotal" :loading="loading"
                    @updatepage="Allchangepage"></pagination>
        </el-tabs>
    </div>
</template>

<script setup>
import { getarticle, getdraft, toToparticle, cancelToparticle ,deleteArticle,SearchArticle} from "@/api/article"
import { ref, reactive, onMounted, inject,watch,onBeforeMount} from 'vue'
import pagination from "@/components/pagination.vue"
import {
    Search,
    Refresh,
    Timer,
    Picture as IconPicture
} from '@element-plus/icons-vue'
import { useRouter } from "vue-router"
import {oneTimegetlables} from "@/api/lable.js"
import moment from "moment"
let router = useRouter()
let reload = inject('reload')
/* 加载数据 */
const loading = ref(false)
let form = reactive({
    articlename: "",
    article_istop:"",
    time: [],
    labels:""
})
let labels = ref([])
/* 全部文章数据的分页 */
const allcurrentPage = ref(1)
const allpageSize = ref(6)
const alltotal = ref(0)
let activeName = ref(1)
let tempcurrentpage = ref(1)
let tempalltotal = ref(6)
let isFirstSearch = true
/* 上方搜索按钮 */
const formRef = ref(null);
/* 修改页脚 */
async function Allchangepage(val) {
    allcurrentPage.value = val
    let alldata
    if (isFirstSearch) {
        if(activeName.value == 1){
            loading.value = true
        alldata = await getarticle({
        page: allcurrentPage.value,
        pageSize: allpageSize.value,
            })
        }else{
            loading.value = true
        alldata = await getdraft({
        page: allcurrentPage.value,
        pageSize: allpageSize.value,
            })
        }
        if (alldata.data.status == 200) {
            loading.value = false
            IntegrationallPrams(alldata.data.data)
        }
    }else{
        loading.value = true
        console.log(allcurrentPage.value);
        let pramas=IntegrationPrams(allcurrentPage.value,allpageSize.value)
        let res=await SearchArticle(pramas)
        console.log(res);
        if(res.data.status==200){
            loading.value = false
            tableData.value = res.data.data.articlelist
            ElMessage({
                message: '查询成功',
                type: 'success',
            })
        }else{
            ElMessage({
                message: res.data.message,
                type: 'error',
            })
        }
    }
    
}
watch([()=>form.articlename,()=>form.article_istop,()=>form.labels,()=>form.time],async(newval)=>{
    let is=newval.every(element => {
        return element.length==0
    });
     if(is){
        isFirstSearch = true
        alltotal.value = tempalltotal.value
        if(activeName.value==1){
            let alldata = await getarticle({
                page: allcurrentPage.value,
                pageSize: allpageSize.value,
            })
            if (alldata.data.status == 200 ) {
                IntegrationallPrams(alldata.data.data)
            }
        }else{
            let alldata = await getdraft({
                page: allcurrentPage.value,
                pageSize: allpageSize.value,
            })
            if (alldata.data.status == 200 ) {
                IntegrationallPrams(alldata.data.data)
            }
        }
    } 
},{
    deep:true
})
/* 删除文章 */
const AllhandleClick = async (data) => {
    let { id } = data
    let res = await deleteArticle({article_id:id})
    if (res.data.status == 200) {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
        reload()
    }
}
onMounted(async () => {
    /* 获取全部的标签信息 */
    let res = await oneTimegetlables()
    if(res.data.status==200){
        labels.value = res.data.data
    }
    loading.value = true
    let alldata = await getarticle({
        page: allcurrentPage.value,
        pageSize: allpageSize.value,
    })
    if (alldata.data.status == 200 ) {
            loading.value = false
            IntegrationallPrams(alldata.data.data)
    } else {
        ElMessage({
            message: alldata.data.message,
            type: 'warning',
        })
    }

})
/* 改变 */
async function handlechangepage(){
    allcurrentPage.value = 1
    let alldata 
    loading.value = true
    if(activeName.value==1){
        alldata = await getarticle({
        page: allcurrentPage.value,
        pageSize: allpageSize.value,
    })
    }else{  
        alldata = await getdraft({
        page: allcurrentPage.value,
        pageSize: allpageSize.value,
        })   
    }
    if(alldata.status == 200){
        loading.value = false
        IntegrationallPrams(alldata.data.data)
    }else {
        ElMessage({
            message: alldata.data.message,
            type: 'warning',
        })
    }
}
/* 随机获取标签状态 */
function getrandmtype() {
    let types = ["info", "danger", "warning"]
    return types[Math.floor(Math.random() * types.length + 1)]
}
/* 全部已发布文章数据 */
let tableData = ref(
    [
        {
            id: '1',
            article_title: 'vue脚手架搭建',
            article_description: 'vue的脚手架的一些安排',
            lables: [{ type: 'info', label: 'Tag 3' },
            { type: 'danger', label: 'Tag 4' },
            { type: 'warning', label: 'Tag 5' },],
            article_cover: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
            article_istop: false,
            createdAt: "2021-02-05",
            updatedAt: "2021-05-07",
        },
    ]
)
/* 改变置顶 */
async function handleChangeswitch(item, isok) {
    let article_id = item.id
    if (isok) {
        /* 文章置顶 */
        let res = await toToparticle({
            article_id
        })
        if (res.data.status == 200) {
            ElMessage({
                message: '修改成功',
                type: 'success',
            })
        } else {
            ElMessage({
                message: res.data.message,
                type: 'error',
            })
        }
    } else {
        /* 文章取消置顶 */
        let res = await cancelToparticle({
            article_id,
        })
        if (res.data.status == 200) {
            ElMessage({
                message: '修改成功',
                type: 'success'
            })
        } else {
            ElMessage({
                message: res.data.message,
                type: 'error',
            })
        }
    }
    reload()
}
/* 整合参数all */
function IntegrationallPrams(alldata) {
    alltotal.value = alldata.count
   if(alldata.count>0){
    tableData.value = alldata.articlelist.map(item => {
        let labless = item.lables.map(item => {
            return {
                type: getrandmtype(),
                label: item
            }
        })
        
        return {
            id: item.id,
            article_title: item.article_title,
            article_description: item.article_description,
            lables: labless,
            article_cover: item.article_cover,
            article_istop: item.article_istop,
            createdAt: moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: moment(item.updatedAt).format('YYYY-MM-DD HH:mm:ss'),
        }
    })
   }
}
/* 文章搜索 */
const onSubmit = async(e,page) => {
    /* 整合参数 {article_title,article_istop,article_status,lable_id,page,pageSize,time} */
    tempcurrentpage.value = allcurrentPage.value
    tempalltotal.value = alltotal.value
    if(form.articlename=='' && form.article_istop=='' && form.time.length==0 && form.labels==''){
        ElMessage.warning('请输入搜索条件')
        return
    }
    if(isFirstSearch){
        allcurrentPage.value = 1
        let pramas=IntegrationPrams(allcurrentPage.value,allpageSize.value)
        loading.value = true
        let res=await SearchArticle(pramas)
        if(res.data.status==200){
            loading.value = false
            tableData.value = res.data.data.articlelist
            ElMessage({
                message: '查询成功',
                type: 'success',
            })
        }else{
            loading.value = false
            ElMessage({
                message: res.data.message,
                type: 'error',
            })
        }
        isFirstSearch = false
    }else{
        let pramas=IntegrationPrams(allcurrentPage.value,allpageSize.value)
        loading.value = true
        let res=await SearchArticle(pramas)
        isFirstSearch = false
        if(res.data.status==200){
            loading.value = false
            tableData.value = res.data.data.articlelist
            ElMessage({
                message: '查询成功',
                type: 'success',
            })
        }else{
            tableData.value = []
            loading.value = false
            ElMessage({
                message: res.data.message,
                type: 'error',
            })
        }


    }
}
/* 整合搜索文章的参数 */
function IntegrationPrams(page,pageSize){
    if(activeName.value==1){
        return {
        article_title:form.articlename,
        article_istop:form.article_istop,
        article_status:1,
        lable_id:form.labels,
        time:form.time,
        page,
        pageSize
        }
    }else{
        return {
        article_title:form.articlename,
        article_istop:form.article_istop,
        article_status:2,
        lable_id:form.labels,
        time:form.time,
        page,
        pageSize
        }
    } 
}
const reset = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
/* 跳转编辑文章 */
const editorarticle = (data) => {
    router.push({
        path: "/article/editarticle",
        query: {
            id: data.id
        }
    })
}
</script>

<style lang="css" scoped>
:deep(.el-form--inline .el-form-item) {
    margin-right: 0px;
}

.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-image__error .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}

.demo-image__error .el-image {
    padding: 0 5px;
    max-width: 150px;
    max-height: 100px;
    width: 100%;
    height: 80px;
}

.demo-image__error .image-slot .el-icon {
    font-size: 30px;
}
</style>